﻿using System;
#if SILVERLIGHT
using System.Windows;
using System.Windows.Data;
using System.Globalization;
#else
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
#endif

namespace Microsoft.PlayerFramework
{
    /// <summary>
    /// IValueConverter used to help Xaml bind an int? value to an int value by simply adding 1 to the value so null == 0.
    /// </summary>
    public class NullIndexConverter : IValueConverter
    {
        /// <inheritdoc /> 
#if SILVERLIGHT
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
#else
        public object Convert(object value, Type targetType, object parameter, string culture)
#endif
        {
            return Convert((int?)value);
        }

        /// <summary>
        /// Converts an int? to an int by adding 1.
        /// </summary>
        /// <param name="value">The nullable int.</param>
        /// <returns>The value + 1. null will return 0.</returns>
        public static int Convert(int? value)
        {
            if (value.HasValue) return value.Value + 1;
            else return 0;
        }

        /// <inheritdoc /> 
#if SILVERLIGHT
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
#else
        public object ConvertBack(object value, Type targetType, object parameter, string culture)
#endif
        {
            return ConvertBack((int)value);
        }

        /// <summary>
        /// Converts an int to a int? by subtracting 1.
        /// </summary>
        /// <param name="value">A zero based int to convert.</param>
        /// <returns>The value - 1. 0 will return null.</returns>
        public static int? ConvertBack(int value)
        {
            if (value == 0) return (int?)null;
            else return value - 1;
        }
    }
}
